package com.example.administrator.yunniuusedcar.view;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.FrameLayout;

import com.example.administrator.yunniuusedcar.R;


/**
 * Created by dance on 2017/12/21.
 * 功能：负责切换显示不同的界面，加载中界面，失败界面，成功界面
 */

public class LoadingLayout extends FrameLayout {

    private View loadingView, errorView, successView;

    public LoadingLayout(Context context) {
        this(context, null);
    }

    public LoadingLayout(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public LoadingLayout(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);

        init();
    }

    /**
     * 初始化
     */
    private void init() {
        //添加3个界面View
        loadingView = View.inflate(getContext(), R.layout.page_loading, null);
        addView(loadingView);

        errorView = View.inflate(getContext(), R.layout.page_error, null);
        errorView.findViewById(R.id.btn_reload).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                //让Fragment重新请求数据
                listener.onReload();
            }
        });
        addView(errorView);

        //由于successView每个界面都不一样，所以提供一个set方法让外界来传递
        hideAll();
    }

    /**
     * 设置sucessView
     * @param view
     */
    public void setSuccessView(View view){
        this.successView = view;
        addView(this.successView);
        hideAll();
    }

    /**
     * 隐藏所有的子View
     */
    private void hideAll(){
        loadingView.setVisibility(INVISIBLE);
        errorView.setVisibility(INVISIBLE);
        if(successView!=null){
            successView.setVisibility(INVISIBLE);
        }
    }

    /**
     * 显示loadingView
     */
    public void showLoading(){
        hideAll();
        loadingView.setVisibility(VISIBLE);
    }

    /**
     * 显示errorView
     */
    public void showError(){
        hideAll();
        errorView.setVisibility(VISIBLE);
    }

    /**
     * 显示sucessView
     */
    public void showSuccess(){
        hideAll();
        if(successView!=null){
            successView.setVisibility(VISIBLE);
        }
    }

    private OnReloadListener listener;
    public void setOnReloadListener(OnReloadListener listener){
        this.listener = listener;
    }
    public interface OnReloadListener{
        void onReload();
    }

}
